package com.cskt.petums.service.impl;

import com.cskt.common.constants.Constants;
import com.cskt.common.entity.pojo.User;
import com.cskt.common.entity.vo.StatusEnum;
import com.cskt.common.entity.vo.UserInfoVO;
import com.cskt.common.exception.BaseException;
import com.cskt.common.utils.RedisKeyUtils;
import com.cskt.petums.mapper.UserMapper;
import com.cskt.petums.service.UserService;
import com.cskt.petums.service.redis.RedisService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;

/**
 * @author admin
 * @date 2023/04/13 16:04
 **/
@Service
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisService redisService;
    @Resource
    private ObjectMapper objectMapper;


    @Override
    public String login(String phone, String sms) {
        try {
            //校验短信验证码
            //String smsKey = PetUmsUtils.generateSmsRedisKey(Constants.Sms.TYPE_REGISTER_OR_LOGIN, phone);
            String smsKey = RedisKeyUtils.formatKeyWithPrefix(String.valueOf(Constants.Sms.TYPE_REGISTER_OR_LOGIN), phone);
            String value = redisService.getValue(smsKey);
            if (value != null && !value.equals(sms)) {
                //验证不成功
                log.warn("短信验证码错误或已失效，phone:{},smsCode:{}", phone, sms);
                return null;
            }
            //判断当前用户是否存在，如果不存在，则创建一个对象，写入到数据库
            User user = userMapper.selectUserByPhone(phone);
            if (ObjectUtils.isEmpty(user)) {
                user = new User();
                user.setAccount(phone);
                user.setUserName(phone);
                user.setCreatedTime(LocalDateTime.now());
                user.setUpdatedTime(LocalDateTime.now());
                int result = userMapper.insertSelective(user);
                if (result == 0) {
                    return null;
                }
            }
            return setToken(user);
        } catch (JsonProcessingException e) {
            throw new BaseException(StatusEnum.COMMON_EXCEPTION);
        }
    }

    /**
     * 生成token，并将用户信息存入redis
     *
     * @param user
     * @return token
     * @throws JsonProcessingException
     */
    @NotNull
    private String setToken(User user) throws JsonProcessingException {
        //先生成token
        String token = UUID.randomUUID().toString().replace("-", "");
        //String tokenKey = PetUmsUtils.generateTokenRedisKey(token);
        String tokenKey = RedisKeyUtils.formatKeyWithPrefix(Constants.Auth.HEADER_TOKEN_KEY_NAME, token);
        //将用户信息存入到redis
        redisService.putValue(tokenKey, objectMapper.writeValueAsString(user), Constants.Time.TOKEN_EFFECTIVE_TIME);
        return token;
    }

    @Override
    public UserInfoVO getUserInfoByToken(String token) {
        try {
            //生成token
            //String tokenKey = PetUmsUtils.generateTokenRedisKey(token);
            String tokenKey = RedisKeyUtils.formatKeyWithPrefix(Constants.Auth.HEADER_TOKEN_KEY_NAME, token);
            User user = objectMapper.readValue(redisService.getValue(tokenKey), User.class);
            //非空判断
            if (ObjectUtils.isEmpty(user)) {
                log.warn("token错误或已失效：{}", token);
                return null;
            }
            //类型转换
            UserInfoVO userInfoVO = new UserInfoVO();
            BeanUtils.copyProperties(user, userInfoVO);
            return userInfoVO;
        } catch (JsonProcessingException e) {
            throw new BaseException(StatusEnum.COMMON_EXCEPTION);
        }
    }

    @Override
    public User getUserById(Long userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    /**
     * 微信登录
     *
     * @param code access_token
     * @return
     */
    @Override
    public String loginWeChat(String code) {
        //try {
        //    //1、先根据code获取用户信息,主要获取access_token和open_id
        //    String accessTokenUrl = generateAccessTokenUrl(code);
        //    log.info("accessTokenUrl:{}", accessTokenUrl);
        //    String weChatResult = restTemplate.getForObject(accessTokenUrl, String.class);
        //    log.info("响应数据：{}", weChatResult);
        //    Map map = objectMapper.readValue(weChatResult, Map.class);
        //    //取出token
        //    String accessToken = map.get("access_token").toString();
        //    //取出openId，用于数据库查询，看用户是否存在
        //    String openId = map.get("openid").toString();
        //    //2、判断当前open_id对应的用户在数据库中是否存在
        //    User user = userMapper.selectUserByOpenId(openId);
        //    if (ObjectUtils.isEmpty(user)) {
        //        //    当用户为空，则创建一个新的用户
        //        user = new User();
        //        // 获取用户信息
        //        String userInfoUrl = generateUserInfoUrl(accessToken, openId);
        //        log.info("userInfoUrl:{}", userInfoUrl);
        //        String userInfo = restTemplate.getForObject(userInfoUrl, String.class);
        //        log.info("获取微信用户信息：{}", userInfo);
        //        Map userInfoMap = objectMapper.readValue(userInfo, Map.class);
        //        user.setOpenId(userInfoMap.get("openid").toString());
        //        user.setUserName(userInfoMap.get(Constants.WeChat.WECHAT_NIKE_NAME_KEY).toString());
        //        user.setHeadUrl(userInfoMap.get(Constants.WeChat.WECHAT_HEAD_IMAGE_URL_KEY).toString());
        //        user.setSex(Integer.valueOf(userInfoMap.get(Constants.WeChat.WECHAT_SEX_KEY).toString()));
        //        user.setCreatedTime(LocalDateTime.now());
        //        user.setUpdatedTime(LocalDateTime.now());
        //        int result = userMapper.insertSelective(user);
        //        if (result == 0) {
        //            log.error("微信注册失败");
        //        }
        //    }
        //    return setToken(user);
        //} catch (Exception e) {
        //    log.error("系统 异常：{}",e.getMessage());
        //    throw new BaseException(StatusEnum.COMMON_EXCEPTION);
        //}
        return null;
    }

    /**
     * 生成获取用户信息url
     *
     * @param accessToken
     * @param openId
     * @return
     */
    //private String generateUserInfoUrl(String accessToken, String openId) {
    //    return new StringBuffer(weChatLoginConfig.getUserInfoUrl()).append("?")
    //            .append("access_token=").append(accessToken).append("&")
    //            .append("openid=").append(openId).append("&")
    //            .append("lang=").append(weChatLoginConfig.getLang())
    //            .toString();
    //}
    //
    ///**
    // * 生成access_token_url
    // *
    // * @param code 第一步获取到的 code
    // * @return
    // */
    //private String generateAccessTokenUrl(String code) {
    //    return new StringBuffer(weChatLoginConfig.getAccessTokenUrl()).append("?")
    //            .append("appid=").append(weChatLoginConfig.getAppid()).append("&")
    //            .append("secret=").append(weChatLoginConfig.getSecret()).append("&")
    //            .append("code=").append(code).append("&")
    //            .append("grant_type=").append(weChatLoginConfig.getGrantType())
    //            .toString();
    //}
}
